<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElForm, ElFormItem, ElInput, ElButton, ElLink, ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { useRouter } from 'vue-router';

// 登录表单数据
const loginForm = reactive({
  phone: '',
  password: ''
});

// 表单验证规则
const formRules: FormRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
};

// 表单引用
const formRef = ref<FormInstance>();

// 路由实例
const router = useRouter();

// 切换到短信登录（可扩展跳转逻辑）
const switchToSmsLogin = () => {
  ElMessage.info('切换到短信验证码登录');
  router.push('/SmsLogin')
};

// 处理登录逻辑
const handleLogin = async () => {
  // 表单校验：校验失败直接返回，终止后续操作
  if (!formRef.value) return;
  try {
    await formRef.value.validate(); // 校验成功才继续
  } catch (err) {
    ElMessage.error('请检查输入内容是否正确');
    return; // 校验失败，不再发送请求
  }

  try {
    const response = await fetch('http://localhost:8020/user/PasswordLogin', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(loginForm)
    });

    // 解析后端返回（无论成功/失败都先解析）
    const result = await response.json();

    // 处理后端返回的业务逻辑（兼容常见格式）
    if (result.code === 0) {
      // 1. 优先从 data 中取 token（多数后端会这样设计），兼容直接在根节点的情况
      const token = result.data?.token || result.token;
      if (token) {
        localStorage.setItem('token', token);
        ElMessage.success('登录成功');
        router.push('/');
      } else {
        ElMessage.error('登录成功，但未获取到 token');
      }
    } else {
      // 2. 后端返回错误（如密码错误），提示具体信息
      ElMessage.error(result.msg || '登录失败：账号或密码错误');
    }
  } catch (error) {
    // 3. 网络错误或解析失败
    console.error('登录请求错误:', error);
    ElMessage.error('网络异常，请稍后重试');
  }
};
</script>

<template>
  <div class="login-container">
    <!-- 登录表单 -->
    <el-form
        ref="formRef"
        :model="loginForm"
        :rules="formRules"
        label-width="80px"
        class="login-form"
    >
      <h2 class="login-title">手机号登录</h2>
      <el-form-item label="手机号" prop="phone">
        <el-input
            v-model="loginForm.phone"
            placeholder="请输入手机号"
            prefix-icon="el-icon-phone"
            maxlength="11"
            clearable
        />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
            show-password
            clearable
        />
      </el-form-item>
      <el-form-item>
        <el-link type="primary" @click="switchToSmsLogin">用短信验证码登录</el-link>
      </el-form-item>
      <el-form-item>
        <el-button
            type="primary"
            class="login-btn"
            @click="handleLogin"
        >
          登录
        </el-button>
      </el-form-item>
      <div class="extra-links">
        <el-link type="primary">找回密码</el-link>
        <el-link type="primary">
          <router-link to="Login" style="text-decoration: none">
          注册账号
          </router-link>
        </el-link>
        <el-link type="primary">更多选项</el-link>
      </div>
    </el-form>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.login-form {
  width: 360px;
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
  font-size: 1.2rem;
  font-weight: 600;
}

.login-btn {
  width: 100%;
  background: #00C853;
}

.extra-links {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
</style>
